"""
从网易大神app爬取每日任务
"""
import time
import os
import shutil
import requests
from datetime import datetime, timedelta
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import email.message
import base64
from PIL import Image


class SkyTask:
    def __init__(self):
        self.qqMail = smtplib.SMTP_SSL("smtp.qq.com", 465)
        self.mailUser = "sunicao@foxmail.com"
        self.mailPass = "xxxxxxx"   # qq邮箱密钥
        self.receiver = "2487994480@qq.com"
        with open('Cookie.txt', 'r') as file:
            cookies = file.read()
        self.headers = {'Accept': 'application/json, text/plain, */*',
                        'Accept-Encoding': 'gzip, deflate, br, zstd',
                        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ru;q=0.7',
                        'Gl-Clienttype': '61',
                        'Gl-Deviceid': '86221409.1717294960',
                        'Gl-Uid': '1445a238b9d14a0f9a30f0c543acae0f',
                        'Gl-X-Xsrf-Token': 'd9dcd351-c39c-4f69-89b9-2d7529c0b3d7',
                        'Origin': 'https://ds.163.com',
                        'Priority': 'u=1, i',
                        'Referer': 'https://ds.163.com/',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
                        'Cookie': cookies
                        }
        self.url = 'https://inf.ds.163.com/v1/web/feed/basic/getSomeOneFeeds?feedTypes=1,2,3,4,6,7,10,11&someOneUid=24dbc317bc1742ab9f89c31a2e1a7b64'
        self.like_url = 'https://inf.ds.163.com/v1/web/like/addOrUpdate'
        self.ratio = 0.5

    def date_now_format(self):
        date_now = datetime.now().strftime("%#m.%d")
        return date_now

    def mk_save_dir(self, date):
        # print(os.getcwd())
        save_path_main = os.path.join(os.getcwd(), '每日任务')
        if not os.path.exists(save_path_main):
            os.mkdir(save_path_main)
        save_path_day = os.path.join(save_path_main, date)
        if not os.path.exists(save_path_day):
            os.mkdir(save_path_day)
        else:
            shutil.rmtree(save_path_day)
            os.mkdir(save_path_day)
        return save_path_day

    def is_picture(self, name):
        pic_type = ['.JPEG', '.PNG', '.BMP', '.TIFF', '.JPG', '.EPS', '.JPE', '.JFIF', '.JFXX', '.SVG',
                    '.webp', '.WMF', '.RAW', '.ICO', '.EMF']
        for i in pic_type:
            if i.lower() in name:
                return True, i.lower()
            else:
                return False, None

    def picture_resize(self, picture, resize_picture):  # 压缩图片，方便在微信的邮箱展示
        img = Image.open(picture).convert('RGB')
        img_x, img_y = img.size
        new_img = img.resize((int(img_x * self.ratio), int(img_y * self.ratio)))
        new_img.save(resize_picture)


    def get_response(self, url, type='Text'):
        response = requests.get(url=url, headers=self.headers)
        if type == 'Text':
            return response.text
        elif type == 'Json':
            return response.json()
        elif type == 'Content':
            return response.content
        else:
            print(f'''请输入正确的返回类型：Text、Json、Content''')

    def get_task_all(self):
        while True:
            data = {}
            response = self.get_response(self.url, type='Json')
            date_now = self.date_now_format()
            # 查看近10条动态是不是最新日期的每日任务
            for i in range(10):
                content = eval(response['result']['feeds'][i]['content'])['body']
                # print(type(content))
                data['title'] = content['title']
                data['longText'] = content['longText']
                if date_now not in data['title']:
                    continue
                else:
                    break

            if date_now not in data['title']:
                print(f'''每日任务还没有更新！！''')
                time.sleep(3600)
                continue

            # 写入文件备用
            with open('longText.txt', 'w', encoding='utf-8') as file:
                file.write(data['longText'])

            email_content = f'''{data['title']}<br>'''  # 邮件正文
            # 获取每日任务图片
            save_path = self.mk_save_dir(date_now)
            task_picture_name = save_path + '\\' + f'''task_total.jpg'''
            task_url = content['media'][0]['url']
            task_img_res = self.get_response(task_url, type='Content')
            with open(task_picture_name, 'wb') as file:
                file.write(task_img_res)
                print(f'''task_total.jpg 保存成功''')

            task_img_base64 = base64.b64encode(task_img_res).decode('utf-8')
            email_content += f'''{date_now}每日任务滴滴<p align="left"><img src="data:image/jpeg;base64,{task_img_base64}" ></p>'''

            # 获取其他信息
            s1 = data['longText'].replace('<strong>', '').replace('</strong>', '').replace('<p align="center">', '')\
                .replace('</p>', '').replace('<p>', '').replace('</a>', '').replace('<a>', '')
            s2 = s1.replace('<img', '$').replace('<a', '$').replace('点击查看', '点击上方查看\n')
            s3 = s2.split('>')
            content_body = {}
            for i in s3:
                if i.strip() != '':
                    temp = i.strip().split('$')
                    jpg = temp[1].split('"')[1]
                    content_body[temp[0]] = jpg
            print(f'''content_body:{content_body}''')

            cnt = 0
            for key in content_body.keys():
                email_content += f'''<br>{key}<br>'''
                is_p = self.is_picture(content_body[key])
                if is_p[0]:
                    other_picture_name = save_path + '\\' + f'''{cnt}{is_p[1]}'''
                    other_img_res = self.get_response(content_body[key], type='Content')
                    # 保存图片到本地
                    with open(other_picture_name, 'wb') as file:
                        file.write(other_img_res)
                        print(f'''{cnt}{is_p[1]} 保存成功''')
                    # 保存图片到邮件正文
                    img_base64 = base64.b64encode(other_img_res).decode('utf-8')
                    email_content += f'''<p align="left"><img src="data:image/jpeg;base64,{img_base64}" ></p>'''
                    cnt += 1
                else:
                    email_content += f'''{content_body[key]}'''

            # 写入文件备用
            with open('data.txt', 'w', encoding='utf-8') as file:
                file.write(str(content_body))
            with open('email_content.txt', 'w', encoding='utf-8') as file:
                file.write(str(email_content))

            return content_body, email_content

    def get_task_special(self):
        while True:
            data = {}
            response = self.get_response(self.url, type='Json')
            date_now = self.date_now_format()
            # 查看近10条动态是不是最新日期的每日任务
            for i in range(10):
                # 给博主点个赞吧~
                id = response['result']['feeds'][i]['id']
                uid = response['result']['feeds'][i]['uid']
                objectId = uid + '.' + id
                with open('objectId.txt', 'w', encoding='utf-8') as file:
                    file.write(objectId)

                content = eval(response['result']['feeds'][i]['content'])['body']
                # print(type(content))
                data['title'] = content['title']
                data['longText'] = content['longText']
                if date_now not in data['title']:
                    continue
                else:
                    break

            if date_now not in data['title']:
                print(f'''每日任务还没有更新！！''')
                time.sleep(3600)
                continue

            # 写入文件备用
            with open('longText.txt', 'w', encoding='utf-8') as file:
                file.write(data['longText'])

            email_content = f'''{data['title']}<br>'''  # 邮件正文
            # 获取每日任务图片
            save_path = self.mk_save_dir(date_now)
            task_picture_name = save_path + '\\' + f'''task_total.jpg'''
            task_url = content['media'][0]['url']
            task_img_res = self.get_response(task_url, type='Content')
            with open(task_picture_name, 'wb') as file:
                file.write(task_img_res)
                print(f'''task_total.jpg 保存成功''')

            # 压缩图片
            resize_path = save_path + '\\' + f'''task_total_resize.jpg'''
            self.picture_resize(task_picture_name, resize_path)
            with open(resize_path, 'rb') as file:
                task_img_resize = file.read()
            task_img_base64 = base64.b64encode(task_img_resize).decode('utf-8')
            email_content += f'''{date_now}每日任务滴滴<p align="left"><img src="data:image/jpeg;base64,{task_img_base64}" "></p>'''

            # 获取其他信息
            s1 = data['longText'].replace('<strong>', '').replace('</strong>', '').replace('<p align="center">', '')\
                .replace('</p>', '').replace('<p>', '').replace('</a>', '').replace('<a>', '').replace('<br>', '')
            s2 = s1.replace('<img', '$').replace('<a', '$')\
                .replace('点击查看', '点击上方查看\n').replace('『每日任务』', '『每日任务』\n')
            s3 = s2.split('>')
            print(f'''s3:{s3}''')
            content_body = {}
            for i in s3:
                if i.strip() != '':
                    temp = i.strip().split('$')
                    jpg = temp[1].split('"')[1]
                    content_body[temp[0]] = jpg
            print(f'''content_body:{content_body}''')

            cnt = 0
            for key in content_body.keys():
                if '日程提醒' in key:   # 老婆大人不需要这个信息
                    continue
                email_content += f'''<br>{key}<br>'''
                is_p = self.is_picture(content_body[key])
                if is_p[0]:
                    other_picture_name = save_path + '\\' + f'''{cnt}{is_p[1]}'''
                    other_img_res = self.get_response(content_body[key], type='Content')
                    # 保存图片到本地
                    with open(other_picture_name, 'wb') as file:
                        file.write(other_img_res)
                        print(f'''{cnt}{is_p[1]} 保存成功''')

                    # 压缩图片
                    resize_path = save_path + '\\' + f'''{cnt}_resize{is_p[1]}'''
                    self.picture_resize(other_picture_name, resize_path)
                    with open(resize_path, 'rb') as file:
                        img_resize = file.read()
                    img_base64 = base64.b64encode(img_resize).decode('utf-8')
                    email_content += f'''<p align="left"><img src="data:image/jpeg;base64,{img_base64}" ></p>'''
                    cnt += 1
                else:
                    email_content += f'''{content_body[key]}'''

            # 写入文件备用
            with open('data.txt', 'w', encoding='utf-8') as file:
                file.write(str(content_body))
            with open('email_content.txt', 'w', encoding='utf-8') as file:
                file.write(str(email_content))

            return content_body, email_content

    def get_task_only(self):   # 一定要在 get_task_special 后运行
        # 从已有的文件中获取每日任务
        date_now = self.date_now_format()
        email_content = f'''【{date_now}每日任务】<br>'''  # 邮件正文
        resize_path = os.path.join(os.getcwd(), '每日任务', date_now, 'task_total_resize.jpg')
        with open(resize_path, 'rb') as file:
            task_img_resize = file.read()
        task_img_base64 = base64.b64encode(task_img_resize).decode('utf-8')
        email_content += f'''{date_now}每日任务滴滴<p align="left"><img src="data:image/jpeg;base64,{task_img_base64}" "></p>'''

        return email_content

    def send_email_special(self):
        email_content = self.get_task_special()[1]
        print(f'''开始发送每日全部信息的邮件...''')
        qqMail = self.qqMail
        qqMail.login(self.mailUser, self.mailPass)
        message = email.message.EmailMessage()
        message['From'] = {self.mailUser}
        message['To'] = {self.receiver}
        message['Subject'] = "光遇每日全部信息滴滴"
        message.set_content(email_content, 'html', 'utf-8')
        try:
            qqMail.sendmail(self.mailUser, self.receiver, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            print(e)
            print("邮件发送失败")

    def send_email_only(self):
        email_content = self.get_task_only()
        print(f'''开始发送只包含每日任务的邮件...''')
        qqMail = self.qqMail
        qqMail.login(self.mailUser, self.mailPass)
        message = email.message.EmailMessage()
        message['From'] = {self.mailUser}
        message['To'] = {self.receiver}
        message['Subject'] = "光遇每日任务滴滴"
        message.set_content(email_content, 'html', 'utf-8')
        try:
            qqMail.sendmail(self.mailUser, self.receiver, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            print(e)
            print("邮件发送失败")


if __name__ == '__main__':
    sky = SkyTask()
    print(sky.headers)
    sky.send_email_special()
    sky.send_email_only()
    # print(sky.get_response(sky.url, 'Text'))







